package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDto;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_USER_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 关注或者取关当前UserId
     *
     * @param followId UserId
     * @param isFollow 是否关注
     * @return Result
     */
    @Override
    public Result follow(Long followId, Boolean isFollow) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();

        // 判断关注或取关
        if (isFollow) {
            // -关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followId);
            boolean isSave = save(follow);
            if (isSave) {
                // -关注成功，将关注用户id存入redis
                stringRedisTemplate.opsForSet().add(FOLLOW_USER_KEY + userId, followId.toString());
            }
        } else {
            // -取关，删除数据
            boolean isSuccess = remove(Wrappers.<Follow>lambdaQuery()
                    .eq(Follow::getUserId, userId)
                    .eq(Follow::getFollowUserId, followId));
            if (isSuccess) {
                // -取关成功，将关注用户id从redis中移除
                stringRedisTemplate.opsForSet().remove(FOLLOW_USER_KEY + userId, followId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 是否关注当前UserId
     *
     * @param followId UserId
     * @return Result
     */
    @Override
    public Result isFollow(Long followId) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 查询用户
        int count = count(Wrappers.<Follow>lambdaQuery()
                .eq(Follow::getUserId, userId)
                .eq(Follow::getFollowUserId, followId));

        return Result.ok(count > 0);
    }

    /**
     * 查询与当前ID的共同关注列表
     *
     * @param id UserId
     * @return Result
     */
    @Override
    public Result followCommons(Long id) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        String k1 = FOLLOW_USER_KEY + userId;
        String k2 = FOLLOW_USER_KEY + id;
        // 求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(k1, k2);
        // 非空判断
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> followIds = intersect.stream().map(Long::parseLong).collect(Collectors.toList());
        // 查询用户信息
        List<UserDto> collect = userService.listByIds(followIds).stream()
                .map(user -> BeanUtil.copyProperties(user, UserDto.class))
                .collect(Collectors.toList());
        return Result.ok(collect);
    }


}
